import axios from "axios";
import {BASE_URL} from "../config/index.js";
import {Message} from "@arco-design/web-vue";
import {RequestCode} from "../apis/RequestCode.js";

const myRequest = axios.create({
    baseURL: BASE_URL,
    timeout: 12000,   //请求超时时间
})

// 全局设置 axios 发送请求带上cookie
myRequest.defaults.withCredentials = true

// 响应拦截器
myRequest.interceptors.response.use( response =>  {
    //未登录 跳转登录页
    if (response.data.code === 40100){
        if (response.config.url !== '/user/current'){
            window.location.href = '/login?redirect=' + location.pathname
        }else{
            window.location.href = '/login'
        }
    }
    return response.data;
}, function (error) {
    Message.error('请求异常：' + error.message);
    return Promise.resolve({
        code: RequestCode.SYSTEM_ERROR.code,
        message: error.message
    });
});

async function getRequest(url){
    let res = await myRequest({
        url,
        method:`GET`
    });
    return res;
}

async function postRequest (url,data){
    let res =  await myRequest({
        url,
        method:`POST`,
        data
    });
    return res;
}


export {myRequest,getRequest,postRequest}